package leaf.science.ui.jogwheel
{

import caurina.transitions.Tweener;

import fl.motion.Animator;
import fl.motion.MotionEvent;

import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.BlurFilter;
import flash.geom.Point;


[Embed(source="../library/JogWheel.swf", symbol="JogWheel")]
public class JogWheel extends Sprite
{
	
	public var thumb:JogWheelThumb;
	public var range:JogWheelRange;
	public var centerPlacer:Sprite;
	public var fg:Sprite;
	public var bg:Sprite;
	
	public var animator:Animator;
	
	private var _value:Number = 0;
	private var _enabled:Boolean = true;
	
	public function JogWheel()
	{
		thumb = new JogWheelThumb();
		addChild( thumb );
		
		range = new JogWheelRange();
		range.x = -223;
		range.y = -223;
		addChildAt( range, this.getChildIndex( fg ));
		
		centerPlacer.visible = false;
		
		this.mouseEnabled = false;
		bg.mouseEnabled = false;
		bg.mouseChildren = false;
		
	}
	
	public function get center():Point
	{
		var c:Point = new Point( centerPlacer.x, centerPlacer.y );
		return( this.localToGlobal( c ));
	}
	
	private function onMouseWheel( evt:MouseEvent ):void
	{
		if( evt.delta > 0 ) value -= 5/360;
		else value += 5/360; 
	}
	
	public function set value( v:Number ):void
	{
		// limit movement to range
		if( v > range.end )
			if( v > 0.5 ) v = 0;
			else v = range.end;
		
		// data change ?
		if( _value == v ) return;

		_value = v;
		thumb.rotation = Math.round( _value*360 );
		dispatchEvent( new Event( Event.CHANGE ));
	}
	
	public function get value():Number
	{
		return( _value );
	}
	
	public function set enabled( value:Boolean ):void
	{
		if( value )
		{
			addEventListener( MouseEvent.MOUSE_WHEEL, onMouseWheel );
			thumb.mouseEnabled = true;
		}
		else
		{
			if( hasEventListener( MouseEvent.MOUSE_WHEEL ))
				removeEventListener( MouseEvent.MOUSE_WHEEL, onMouseWheel );
			thumb.mouseEnabled = false;
		}
	}
	
	public function get enabled():Boolean
	{
		return( _enabled );
	}
	
	public function startTransitionIn ():void
	{
		animator = new JogWheelAnimatorIn(this);
		animator.addEventListener(MotionEvent.MOTION_END, onTransitionComplete);
	}
	
	public function startTransitionOut ():void
	{
		filters = [new BlurFilter(0,0,3)];
		Tweener.addTween(this, {_blur_blurX:20, _blur_blurY:20, time:0.8});
		Tweener.addTween(this, {alpha:0, time:0.8, delay:0.2, onComplete:onTransitionComplete});
	}
	
	
	private function onTransitionComplete (evt:Event = null):void
	{
		dispatchEvent(new MotionEvent(MotionEvent.MOTION_END));
	}
	
	public var onKnobTweenEnd:Function = new Function();
}
}